/**
 * 联动下拉框方法。此联动下拉框要求appendValues的值为固定格式
 * 此格式用json构建。是一个对象。对象包括多个键值对。
 * 键值对的格式：
 *      键：当前select的value
 *      值：此select的value值所关联的下一个select的value和text组成的对象数组。
 * 比较拗口，大家可以参照demo
 *
 * 需要在select里面添加一个associateId属性，表示与此select相关联的下一个select的id
 * 注：所有关联的下拉框必须提供一个id，有相应的用途
 * @param selectObj 当前下拉框
 * @param appendValues 给下一个联动下拉框赋的值
 */

function AssoSelObj(o) {
    this.editor = o;
}

AssoSelObj.prototype.onReady = function() {
    var $sel = jQuery(this.editor);
	var treeValueAttr = $("select",$sel).first().attr("treeValue");
	if(treeValueAttr){
		eval("var treeValues = " + treeValueAttr);
		initAssoTreeSel($("select",$sel).first(),treeValues);
	}
}

function associateNextSel(selectObj, appendValues) {
    //获得当前下拉框的值
    var $selectObj = $(selectObj);
    var va = $selectObj.find('option:selected').val();
    var opsv = appendValues[va];
    var selId = "#" + $selectObj.attr('associateId');
    var selApp = $(selId);

    //定义命名空间，目的存放添加的联动的option，以便后面删除用
    if (!window.vsassociatesels) {
        window.vsassociatesels = [];
    }
    if (!window.vsassociatesels[$selectObj.attr("id")]) {
        window.vsassociatesels[$selectObj.attr("id")] = [];
    }

    var childSelId = $selectObj.attr("id");

    //遍历后面所有的下拉框，reset
    while (childSelId) {
        var previd = null;
        var childSelAssId = $("#" + childSelId).attr("associateId");
        while (previd = window.vsassociatesels[childSelId] ? window.vsassociatesels[childSelId].pop() : null) {
            $("#" + childSelAssId + " option[value='" + previd + "']").remove();
        }

        childSelId = $("#" + childSelId).attr("associateId");
    }

    var orderByText = selApp.attr("orderByText");
    var asc = selApp.attr("asc");

    if (typeof orderByText != 'undefined') {
        if (orderByText.toLowerCase() == "true") {
            orderByTextFunc(opsv, asc);
        } else {
            orderByValueFunc(opsv, asc);
        }
    }

    //添加option选项
    for (var i = 0; i < (opsv ? opsv.length : 0); i++) {
        window.vsassociatesels[$selectObj.attr("id")].push(opsv[i].value);
        selApp.append("<option value='" + opsv[i].value + "'>" + opsv[i].text + "</option>");
    }
}

function initAssoTreeSel(selectObj, treeValues){
	if(treeValues.item && treeValues.item.length > 0){
		var items = treeValues.item;
		
		//调用排序
	    var orderByText = selectObj.attr("orderByText");
	    var asc = selectObj.attr("asc");

	    if (typeof orderByText != 'undefined') {
	        if (orderByText.toLowerCase() == "true") {
	            orderByTextFunc(items, asc);
	        } else {
	            orderByValueFunc(items, asc);
	        }
	    }
		
		for(var i=0; i< items.length; i++){
			selectObj.append("<option value='" + items[i].id + "' isappend='true'>" + items[i].text + "</option>");
		}
		selectObj[0].treeValue = treeValues;
		selectObj[0].onchange = function(event){associateNextTreeSel($("#" + this.id),this.treeValue)};
		selectObj[0].onchange();//接着选中当前的
	}else {
		$("option",selectObj).each(function(){
			if($(this).attr("isappend")){
				$(this).remove();
			}
		});
		
		if(selectObj.attr("associateId")){
			var assoSel = $("#" + selectObj.attr("associateId"));
			initAssoTreeSel(assoSel,{});
		}
	}
}

function associateNextTreeSel(selectObj, treeValues) {
	if(document.getElementById(selectObj.attr("associateId"))){
		var assoSel = $("#" + selectObj.attr("associateId"));
		var items = treeValues.item;
		for(var i=0; i< items.length; i++) {
			if($("option:selected",selectObj).val() == items[i].id){
					initAssoTreeSel(assoSel,items[i]);
					break;
			}else{
				initAssoTreeSel(assoSel,{});
			}
		}
	}
}

/**
 * 通过ajax进行连动
 * @param selectObj
 * @param url
 */
function ajaxAssoSel(selectObj, url) {
    $.ajax({
        type: 'post',
        url: url,
        data: "selectedValue=" + $(selectObj).find('option:selected').val(),
        dataType: 'json',
        success: function(data) {
            associateNextSel(selectObj, data);
        },
        error: function(data) {
            alert("获取数据发生错误！ %>_<%");
        }
    })
}

function orderByValueFunc(opsv, asc) {
    if (typeof opsv == "undefined") {
        return opsv;
    }
    
    if (typeof asc != 'undefined' && asc.toLowerCase() == "false") {
        opsv.sort(localeCDesValue);
    } else {
        opsv.sort(localeCValue);
    }

    return opsv;
}

function localeCValue(a, b) {
    if (typeof a == "undefined" || typeof b == "undefined") {
        return 0;
    }
    return a['value'].localeCompare(b['value']);
}

function localeCDesValue(a, b) {
    if (typeof a == "undefined" || typeof b == "undefined") {
        return 0;
    }
    return b['value'].localeCompare(a['value']);
}

function orderByTextFunc(opsv, asc) {
    if (typeof opsv == "undefined") {
        return opsv;
    }
    
    if (typeof asc != 'undefined' && asc.toLowerCase() == "false") {
        opsv.sort(localeCDesText);
    } else {
        opsv.sort(localeCText);
    }

    return opsv;
}

function localeCText(a, b) {
    if (typeof a == "undefined" || typeof b == "undefined") {
        return 0;
    }
    return a['text'].localeCompare(b['text']);
}

function localeCDesText(a, b) {
    if (typeof a == "undefined" || typeof b == "undefined") {
        return 0;
    }
    return b['text'].localeCompare(a['text']);
}